package com.example.seckill.controller;

import com.example.seckill.common.RedisKey;
import com.example.seckill.common.Result;
import com.example.seckill.entity.SeckillGoods;
import com.example.seckill.entity.SeckillOrder;
import com.example.seckill.service.SeckillService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api/seckill")
public class SeckillController {

    @Autowired
    private SeckillService seckillService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @GetMapping("/goods")
    public Result<List<SeckillGoods>> listGoods(@RequestParam(required = false) Long userId) {
        return seckillService.listGoods(userId);
    }

    @PostMapping("/{goodsId}")
    public Result<SeckillOrder> seckill(@PathVariable Long goodsId, @RequestParam Long userId) {
        log.info("收到秒杀请求 - userId: {}, goodsId: {}", userId, goodsId);
        return seckillService.seckill(userId, goodsId);
    }

    @GetMapping("/order/{orderId}")
    public Result<SeckillOrder> getOrder(@PathVariable Long orderId) {
        return seckillService.getOrder(orderId);
    }

    @GetMapping("/order/result")
    public Result<Long> getOrderResult(@RequestParam Long userId, @RequestParam Long goodsId) {
        String orderKey = RedisKey.SECKILL_ORDER_PREFIX + userId + ":" + goodsId;
        Object value = redisTemplate.opsForValue().get(orderKey);
        Long orderId = null;
        if (value != null) {
            if (value instanceof Integer) {
                orderId = ((Integer) value).longValue();
            } else if (value instanceof Long) {
                orderId = (Long) value;
            }
        }
        return Result.success(orderId);
    }
} 